<template>
  <div class="teamSingle">
    <div class="title">{{$t('instrumentTools.dashboardPreview')}}</div>
    <div class="partOne">
      <div class="partOneHeader">
        <div class="percent">{{$t('instrumentTools.productStage')}}</div>
        <div class="select">
          <a-radio-group v-model="radioValue" @change="onChange">
            <a-radio-button value="1">{{$t('instrumentTools.btn.all')}}</a-radio-button>
            <a-radio-button  value="2">{{$t('instrumentTools.btn.conscientious')}}</a-radio-button>
            <a-radio-button  value="3">{{$t('instrumentTools.btn.participating')}}</a-radio-button>
          </a-radio-group>
        </div>
      </div>
      <fixed-table :tableDate="tableDate"></fixed-table>
    </div>
    <div class="partTwo">
      <div class="chartFirst">
        <div class="chartTitle">{{$t('instrumentTools.projectHealth')}}</div>
        <!-- <chart-box :chartData="healthStatusData" :id="'healthy'" :color="['#4ccb72','#fad336','#ff7978']" :allLength="allLength"></chart-box> -->
        <chart-box :chartData="healthStatusData" :id="'healthy'" :color="healthyColor" :allLength="allLength" :titleData="['项目数占比','健康度']"></chart-box>
      </div>
      <div class="chartSec">
        <div class="chartTitle">{{$t('instrumentTools.closureOfProjectProblems')}}</div>
        <chart-box-bar  :id="'queClosed'" :barData="itemIssueClosedData"></chart-box-bar>
      </div>
    </div>
    <div class="partTwo partThree">
      <div class="chartFirst">
        <div class="chartTitle">{{$t('instrumentTools.proportionOfNodesInThisMonth')}}</div>
       <chart-box :chartData="currentMonthTaskRateData" :id="'currentMonth'" :allLength="currentMonthLength" :titleData="['项目数占比','当月项目任务']" :color="currentMonthTaskRateColor"></chart-box>
      </div>
      <div class="chartFirst">
        <div class="chartTitle">{{$t('instrumentTools.planningProjectInitiation')}}</div>
        <chart-box :chartData="itemLxqkData" :id="'lxqk'" :color="itemLxqkColor" :titleData="['项目立项','项目规划']" :allLength="xmlxLength"></chart-box>
        <!-- <chart-box :chartData="healthStatusData" :id="'lxqk'"></chart-box> -->
      </div>
       <div class="chartFirst">
         <div class="chartTitle">{{$t('instrumentTools.distributionOfProjectCategories')}}</div>
         <chart-box :chartData="projectTypeData" :id="'projectType'" :allLength="allLength" :titleData="['项目数占比','项目大类']" :color="protypeColor"></chart-box>
      </div>
    </div>
  </div>
</template>
<script>
import chartBox from "./chartBox.vue";
import chartBoxBar from "./chartBoxBar.vue";
import FixedTable from './fixedTable.vue';
import { getCurrentMonthTaskRate, getProjectIssueCloseCase, selectProjectApprovalCase } from'@/api/qualityInfoSystem.js'
import {
  getProjectList, 
  getProjectCaches, 
} from "@/api/projectManage.js"
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
let userId = userinfo.loginName
export default {
  name: "teamSingle",
  components: {
    chartBox,
    chartBoxBar,
    FixedTable
  },
  data() {
    return {
      tabType: "ALL",
      radioValue: '1',
      filterData: [], //项目列表数据筛除已结束等状态
      allLength: null,
      mangerLength: null,
      joinLength: null,
      fintableLength: null,
      tableDate: [],
      nodeTitle: [],
      chargeDate: [],
      partticipate: [],
      healthStatusData: [
      ], //健康状态
      healthyColor: [],
      projectTypeData: [], //项目大类
      currentMonthTaskRateData: [
        {
          name: "已完成",
          value: 0,
          color: "#4ccb73"
        },
        {
          name: "未完成",
          value: 0,
          color: "#e2f2e8"
        }
      ],
      xmlxLength: 10,
      currentMonthTaskRateColor: [ "#4ccb73", "#e2f2e8"],
      currentMonthLength: null,
      protypeColor: ["#39A0FF","#37cbcb","#4ccb72","#fad336","#f3637c","#9760e2"],
      itemIssueClosedData: [],
      itemLxqkData: [
        {
          name: "待立项",
          value: 0,
        },
        {
          name: "执行中",
          value: 0,
        },
        {
          name: "已结项",
          value: 0,
        }
      ], //规划项目立项情况
      itemLxqkColor: ["#34ccc9","#3da0fe","#e2e2e2"],
    }
  },
  mounted() {
    this.getTableDataParams("ALL")
    this.getCurrentMonthTaskRateData()
    this.protypeColor = this.protypeColor.concat(['#FDA085','#4CD0DD','#FBC2EB','#96E6A1','#E2EBF0','#FFB199','#C1C161'])
  },
  watch: {
    filterData: {
      handler(v) {
        if(v && v.length) {
          this.getDeal()
          // this.getChartDate()
        }
      },
      deep: true
    },
    radioValue: {
      handler(v) {
        if(v == 1) {
          if(this.nodeTitle && this.nodeTitle.length) {
            this.$set(this,"tableDate",this.nodeTitle)
          } else {
            this.getTableDataParams("ALL")
          }
        } else if (v == 2) {
          if(this.chargeDate && this.chargeDate.length) {
            this.$set(this,"tableDate",this.chargeDate)
          } else {
            this.getTableDataParams("MANAGER")
          }
        } else if (v == 3) {
          if(this.partticipate && this.partticipate.length) {
             this.$set(this,"partticipate",this.partticipate)
          } else {
            this.getTableDataParams("JOIN")
          }
        }
        // MANAGER  JOIN
      }
    }
  },
  methods: {
    getCurrentMonthTaskRateData() {
      getCurrentMonthTaskRate({userId}).then(res => {
        if( res && res.status == 200 ) {
          if( res.data.success == true || res.data.success == 'true' ) {
            // console.log(res.data.data);currentMonthTaskRateData
            const data = res.data.data[0]
            this.$set(this.currentMonthTaskRateData[0],"value",Number(data.completedCount || 0))
            this.$set(this.currentMonthTaskRateData[1],"value",Number(data.toBeCompletedCount || 0))
            this.currentMonthLength = Number(data.completedCount || 0) + Number(data.toBeCompletedCount || 0)
          } else {
            this.$message.error(res.data.message || "请求数据失败")
          }
        } else {
          this.$message.error(res.data.message || "请求数据失败")
        }
      })
    },
    onChange(val) {
      this.radioValue = val.target.value
    },
    // 2.获取数据
    getTableDataParams(tabType) {
      this.loadVisible = true
      let data = {
        "type": tabType
      }
      getProjectList(data).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.data && res.data.data.length > 0) {
            let arr = res.data.data
            this.getTableData(arr,tabType)
            if(tabType === 'ALL') {
              this.getItemIssuesData(arr)
            }
          } else {
            this.loadVisible = false
            this.tableData = []
          }
        } else {
          this.tableData = []
        }
      });
    },
    getTableData(paramsData,tabType) {
      getProjectCaches(paramsData).then(res => {
        if (res.status === 200) {
          if (res.data && res.data.length > 0) {
            const data = res.data.filter(function(item) {
              return  item.state != '已验收'  &&  item.state != '已结束' &&  item.state != '废弃' &&  item.state != '暂停'
            })
            this.$set(this,"filterData", data)
            this.$nextTick(function() {
              if(tabType == 'ALL') {
                this.allLength = this.filterData.length
                this.fintableLength = this.filterData.length
                this.getChartDate(this.filterData,"currentnode",tabType)
                this.getChartDate(this.filterData,"healthStatus")
                this.getChartDate(this.filterData,"projectType")
              } else {
                if(tabType == 'MANAGER') {
                  this.mangerLength = this.filterData.length
                } else if (tabType == 'JOIN') {
                  this.joinLength = this.filterData.length
                }
                this.getChartDate(this.filterData,"currentnode",tabType,this.filterData.length)
              }
              
            })
          } else {
            this.loadVisible = false
          }
        } else {
          this.searchData = []
          this.loadVisible = false
          this.$message.error('获取数据失败')
        }
      }).catch(error => {
        this.searchData = []
        this.loadVisible = false
        this.$message.error('获取数据接口异常')
      })
    },
    getItemIssuesData(paramsData) {
      // const _this = this
      getProjectIssueCloseCase(paramsData).then(res => {
        if(res.status === 200) {
          if (res && res.data && res.status == 200) {
            if (res.data.length > 0) {
              this.itemIssueClosedData = res.data
            } else {
              this.itemIssueClosedData = []
            }
          } else {
            this.itemIssueClosedData = []
          }
        } else {
          this.$message.error(res.data.message || "请求失败")
        }
      }).catch(error => {
        this.$message.error('获取数据接口异常')
        this.itemIssueClosedData = []
      })
      //规划项目立项情况  itemLxqkData
      selectProjectApprovalCase().then( res => {
        if(res && res.data && res.status == 200) {
          this.xmlxLength = Number(res.data.notApproval) + Number(res.data.approvalIng) + Number(res.data.endApproval)
          this.$set(this.itemLxqkData[0],"value",res.data.notApproval  ? Number(res.data.notApproval) : 0)
          this.$set(this.itemLxqkData[1],"value",res.data.approvalIng  ? Number(res.data.approvalIng) : 0)
          this.$set(this.itemLxqkData[2],"value",res.data.endApproval  ? Number(res.data.endApproval) : 0)
        } else {
          this.$message.error(res.message || "请求失败")
        }
      })
    },
    getDeal() {
      //根据当前节点获取表格数据 CURRENTNODE   
      // this.getChartDate(this.filterData,"currentnode")
      //健康度 healthStatus
      //项目大类 projectType
      // this.getChartDate(this.filterData,"projectType")
    },
    getChartDate(data,key,type) {
      let obj = {}
      for( let i= 0; i < data.length; i++) {
        var item = data[i][key]
        if(item) {
          if(obj[item]) {
            obj[item].push(item)
          } else {
            obj[item] = []
            obj[item].push(item)
          }
        }
      }
      this.getDateFinal(obj,key,type)
    },
    getDateFinal(obj,key,type) {
      var dataLength = null
      if(key == 'currentnode') {
         dataLength = type == 'ALL' ? this.allLength : (type == 'MANAGER' ? this.mangerLength : this.joinLength)
      }
      const data = [], _this = this // title = [],
      for(var keyVal in obj) {
        // if(key == 'currentnode') {
        //   title.push(keyVal)
        // }
        const keyObj = {}
        if( key == 'healthStatus' ) {
          keyObj.name = keyVal  == 'UNAVAILABLE' ? "灰灯" : (  keyVal  == 'RED' ? '红灯' : (  keyVal  == 'YELLOW' ? '黄灯' : '绿灯') )
          keyObj.index = keyVal  == 'UNAVAILABLE' ? 4 : (  keyVal  == 'RED' ? 3 : (  keyVal  == 'YELLOW' ? 2 : 1) )
          keyObj.color = keyVal  == 'UNAVAILABLE' ? 'gray' : (  keyVal  == 'RED' ? '#ff7978' : (  keyVal  == 'YELLOW' ? '#fad337' : "#4ccb73") )
        } else {
          keyObj.name = keyVal
        }
        if(key == 'currentnode') {
          keyObj.percent = (obj[keyVal].length/dataLength*100).toFixed(2) + "%"
        }
        keyObj.value = obj[keyVal].length
        keyObj.length = this.getWidth(keyVal)*7.5 + 40
        data.push(keyObj)
      }
      if(key == 'currentnode') {
        // this.$set(this,"nodeTitle", title)
        this.getDealTableData(data,type)
      } else if(key == 'healthStatus') {
        data.sort((a, b) => a.index - b.index)
        data.forEach(function(item) {
          _this.healthyColor.push(item.color)
        })
        this.$set(this,"healthStatusData",data)
      } else if( key == 'projectType') {
        this.$set(this,"projectTypeData", data)
      }
    },
    getWidth(str){
      var len = 0;    
      for (var i=0; i<str.length; i++) { 
        if (str.charCodeAt(i)>127 || str.charCodeAt(i)==94) {    
          len += 2;    
        } else {    
          len ++;    
        }    
      }  
      return len;  
    },
    getDealTableData(data,type) {
      this.$set(this,"tableDate", data)
      if( type == 'ALL') {
        this.$set(this,"nodeTitle", data)
      } else if (type == 'MANAGER') {
        this.$set(this,"chargeDate", data)
      } else if (type == 'JOIN') {
        this.$set(this,"partticipate", data)
      }
    }
  },
  
};
</script>
<style lang="less" scoped>
.teamSingle {
   height: 100%;
  //  overflow: hidden;
   width: 100%;
  // padding: 0 20px;
  // padding-top: 10px;
  .title {
    background-color: #fff;
    margin-bottom: 10px;
    font-weight: 700;
    font-size: 16px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    border-radius: 4px;
  }
  .partOne {
    background: #fff;
    padding: 10px 0;
    border-radius: 4px;
    .partOneHeader {
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      padding-bottom: 6px;
      margin-bottom: 10px;
      border-bottom: 1px solid #e7e7e7;
      .select {
        // width: 10vw;
        /deep/.ant-radio-button-wrapper-checked {
          background: #386bd7;
          color: #fff
        }
      }
      .percent {
        font-weight: 700;
        font-size: 14px;
        line-height: 32px;
      }
    }
    
  }
  .partTwo {
    margin-top: 10px;
    height: calc( 50% - 122px);
    // height: 300px;
    border-radius: 4px;
    .chartTitle {
      height: 36px;
      font-weight: 600;
      font-size: 14px;
      line-height: 36px;
      padding: 0 20px;
      border-bottom: 1px solid #e7e7e7;
    }
    &>div {
      display: inline-block;
      height: 100%;
    }
    .chartFirst {
      width: 32.5%;
      background: #fff;
      margin-right: 0.8%;
      margin-bottom: 10px;
    }
    .chartSec {
      width: 66.7%;
      background: #fff;
    }
  }
  .partThree {
    margin-bottom: 20px;
    .chartFirst:nth-child(3) {
      width: 33.4%;
      margin-right: 0;
    }
  }
}
.chartFirst {
  vertical-align: top;
}
</style>